﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlServer.TransactSql.ScriptDom;

namespace Chaotic.Module.DBTool.Common
{
    public class TableAliasVisitor: TSqlFragmentVisitor
    {
        public List<TableReferenceInfo> TableAliases = new List<TableReferenceInfo>();

        public override void Visit(NamedTableReference node)
        {
            var info = new TableReferenceInfo
            {
                Schema = node.SchemaObject.SchemaIdentifier?.Value,
                TableName = node.SchemaObject.BaseIdentifier.Value,
                Alias = node.Alias?.Value,
                StartLine = node.StartLine,
                StartColumn = node.StartColumn
            };

            TableAliases.Add(info);
            base.Visit(node);
        }
    }
    public class TableReferenceInfo
    {
        public string Schema { get; set; }
        public string TableName { get; set; }
        public string Alias { get; set; }
        public int StartLine { get; set; }
        public int StartColumn { get; set; }

        public override string ToString()
            => $"[{Schema}].[{TableName}]{(Alias != null ? $" AS {Alias}" : "")}";
    }
}
